package com.jushu.storbox;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.jushu.storbox.adapter.FolderBrowserAdapter;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DirectoryManager;
import com.jushu.storbox.util.DeviceUtil;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.FileUtil;
import com.jushu.storbox.util.LogUtil;

/**
 * Folder browser
 */
public class FolderBrowserActivity extends BaseTitleActivity {

	private final static int MOVE_DATA_SUCCESS = 0x0100;

	private final static int MOVE_DATA_FAILURE = 0x0101;
 
	/** ListView for all files */
	private ListView lv_all_files;

	private ArrayList<File> datas = new ArrayList<File>();

	private File mCurrentDir = null;

	private FolderBrowserAdapter adapter;

	private File rootDir;

	/** activity TAG */
	private final static String LOG_TAG = "FolderBrowserActivity";

	private final static List<File> storageList = new ArrayList<File>();

	private enum StorageType {
		SINGLE_TYPE, MUILTY_TYPE, NOTHIONG_TYPE;
	}

	StorageType storageType = StorageType.NOTHIONG_TYPE;

	Handler uiHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MOVE_DATA_SUCCESS:
				saveCatchPathAndReturn();
				break;

			case MOVE_DATA_FAILURE:
				Toast.makeText(FolderBrowserActivity.this, R.string.cache_path_move_fail, Toast.LENGTH_SHORT).show();
				break;

			default:
				super.handleMessage(msg);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.i(LOG_TAG, "onCreate()");
		isSDCardExist();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_all_selfolder);
		switchTypeTwo();
		setCurrentTitle(R.string.setting_cache_path);
		setRightText(R.string.lock_save_password);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG, FolderBrowserActivity.this);
		findViews();
		setListeners();
		setAdapter();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LogUtil.i(LOG_TAG, "onDestroy()");
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
	}

	private void isSDCardExist() {
		List<File> tempList = DeviceUtil.instance().getStorageList(FolderBrowserActivity.this);
		storageList.clear();
		storageList.addAll(tempList);
		if (storageList.isEmpty()) {
			rootDir = null;
			storageType = StorageType.NOTHIONG_TYPE;
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG).show();
		} else if (storageList.size() == 1) {
			rootDir = storageList.get(0);
			storageType = StorageType.SINGLE_TYPE;
		} else if (storageList.size() > 1) {
			rootDir = null;
			storageType = StorageType.MUILTY_TYPE;
		}
	}

	private void findViews() {
		lv_all_files = (ListView) findViewById(R.id.lv_all_files);
	}

	private void setListeners() {
		lv_all_files.setOnItemClickListener(new OnItemClickListenerImpl());
	}

	@Override
	protected void onLeftClicked(View clickView) {
		if (storageType == StorageType.NOTHIONG_TYPE) {
			// setLeftButtonClickable(false);
			setRightButtonClickable(false);
		} else if (storageType == StorageType.SINGLE_TYPE) {
			if (mCurrentDir.equals(rootDir)) {
				super.onLeftClicked(clickView);
				this.finish();
			} else {
				browseToParent(mCurrentDir);
			}
		} else if (storageType == StorageType.MUILTY_TYPE) {
			if (rootDir == null) {
				// setLeftButtonClickable(false);
				setRightButtonClickable(false);
				this.finish();
			} else if (mCurrentDir.equals(rootDir)) {
				// setLeftButtonClickable(false);
				setRightButtonClickable(false);
				rightOperation.setVisibility(View.GONE);
				setCurrentTitle(R.string.setting_cache_path);
				datas.clear();
				rootDir = null;
				mCurrentDir = null;
				datas.addAll(storageList);
				notifyDataSetChanged();
			} else {
				setLeftButtonClickable(true);
				setRightButtonClickable(true);
				rightOperation.setVisibility(View.VISIBLE);
				browseToParent(mCurrentDir);
			}
		}
	}

	@Override
	protected void onRightClicked(View clickView) {
		String targetPath = mCurrentDir.getAbsolutePath();
		String currentPath = DirectoryUtil.getCurrentCachePath(FolderBrowserActivity.this);
		if (currentPath.equals(targetPath)) {
			Toast.makeText(FolderBrowserActivity.this, R.string.cache_path_no_change, Toast.LENGTH_SHORT).show();
			return;
		}

		final File sFile = new File(currentPath + ClientConfig.CACHE_CONTEXT);
		final File dFile = new File(targetPath);// + ClientConfig.CACHE_CONTEXT
		if (new File(dFile, ClientConfig.CACHE_CONTEXT).exists()) {
			Toast.makeText(FolderBrowserActivity.this, R.string.cache_path_exist_same, Toast.LENGTH_SHORT).show();
			return;
		}
		
		if(sFile.isDirectory() && FileUtil.targetIsSelfChild(sFile, dFile)){
			Toast.makeText(FolderBrowserActivity.this, R.string.move_target_is_selfsub, Toast.LENGTH_SHORT).show();
			return;
		}
		
		new Thread() {
			@Override
			public void run() {
				boolean successFLag = FileUtil.moveSourceToTargetFolder(sFile, dFile);
				if (!successFLag) {
					uiHandler.sendEmptyMessage(MOVE_DATA_FAILURE);
				} else {
					FileUtil.deleteAll(sFile);
					uiHandler.sendEmptyMessage(MOVE_DATA_SUCCESS);
				}
			}
		}.start();

		super.onRightClicked(clickView);
	}

	@Override
	protected void setLeftButtonClickable(boolean clickable) {
		if (clickable) {
			returnIcon.setVisibility(View.VISIBLE);
		} else {
			returnIcon.setVisibility(View.GONE);
		}
		super.setLeftButtonClickable(clickable);
	}

	private void saveCatchPathAndReturn() {
		DirectoryUtil.saveCachePath(this, mCurrentDir.getAbsolutePath());
		Intent data = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString("mCurrentDir", mCurrentDir.getAbsolutePath());
		data.putExtra("result", bundle);
		setResult(MessageCode.RESULT_CODE_CACHE_FOLDER, data);
		FolderBrowserActivity.this.finish();
	}

	private void setAdapter() {
		setLeftButtonClickable(true);
		datas.clear();
		switch (storageType) {
		case MUILTY_TYPE:
			datas.addAll(storageList);
			mCurrentDir = null;
			setRightButtonClickable(false);
			rightOperation.setVisibility(View.GONE);
			break;

		case SINGLE_TYPE:
			List<File> folderList = DirectoryManager.getInstance().getFolderList(rootDir);
			Collections.sort(folderList);
			datas.addAll(folderList);
			mCurrentDir = rootDir;
			setRightButtonClickable(true);
			break;

		case NOTHIONG_TYPE:
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG).show();
			setRightButtonClickable(false);
			break;

		default:
			break;
		}
		adapter = new FolderBrowserAdapter(datas, lv_all_files, this);
		lv_all_files.setAdapter(adapter);
	}

	/**
	 * @param location
	 */
	private synchronized void browseToParent(final File location) {
		if (storageType == StorageType.NOTHIONG_TYPE) {
			return;
		}

		if (null == location) {
			return;
		}

		if (storageType == StorageType.SINGLE_TYPE) {
			File parentFile = location.getParentFile();
			if (parentFile.equals(rootDir)) {
				// setLeftButtonClickable(false);
			} else {
				setLeftButtonClickable(true);
				if (!location.isDirectory()) {
					return;
				}
			}
			mCurrentDir = parentFile;

			if (mCurrentDir.equals(rootDir)) {
				setCurrentTitle(R.string.setting_cache_path);
			} else {
				setCurrentTitle(mCurrentDir.getName().compareTo("") == 0 ? mCurrentDir.getPath() : mCurrentDir.getName());
			}
			datas.clear();
			datas.addAll(DirectoryManager.getInstance().getFolderList(mCurrentDir));
		} else if (storageType == StorageType.MUILTY_TYPE) {
			datas.clear();
			if (rootDir == null) {
				setLeftButtonClickable(false);
				setCurrentTitle(R.string.setting_cache_path);
				datas.addAll(storageList);
			} else if (location.equals(rootDir)) {
				// setLeftButtonClickable(false);
				setRightButtonClickable(false);
				setCurrentTitle(R.string.setting_cache_path);
				rootDir = null;
				datas.addAll(storageList);
			} else {
				File parentFile = location.getParentFile();
				if (parentFile != null) {
					mCurrentDir = parentFile;
					setCurrentTitle(mCurrentDir.getName().compareTo("") == 0 ? mCurrentDir.getPath() : mCurrentDir.getName());
					datas.addAll(DirectoryManager.getInstance().getFolderList(mCurrentDir));
				} else {
					datas.addAll(storageList);
				}
			}
		}

		notifyDataSetChanged();
	}

	/**
	 * @param location
	 */
	private synchronized void browseToChild(final File location) {
		setLeftButtonClickable(true);
		setRightButtonClickable(true);
		if (!location.isDirectory()) {
			mCurrentDir = location.getParentFile();
			return;
		} else {
			mCurrentDir = location;
		}

		setCurrentTitle(mCurrentDir.getName().compareTo("") == 0 ? mCurrentDir.getPath() : mCurrentDir.getName());

		datas.clear();
		datas.addAll(DirectoryManager.getInstance().getFolderList(mCurrentDir));
		notifyDataSetChanged();
	}

	private class OnItemClickListenerImpl implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			File item = adapter.getItem(position);
			if (!item.isFile()) {
				if (rootDir == null) {
					File temp = null;
					while(true){
						temp = new File(item.getAbsolutePath()+"/"+System.currentTimeMillis()+FolderBrowserActivity.this.getPackageName());
						if(!temp.exists()){
							try {
								temp.createNewFile();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}finally {
								break;
							}
						}
					}
					if(!temp.exists()) {
						Toast.makeText(FolderBrowserActivity.this, R.string.cache_path_did_not_come, Toast.LENGTH_SHORT).show();
						return;
					}else {
						temp.delete();
					}
					rootDir = item;
					rightOperation.setVisibility(View.VISIBLE);
				}
				browseToChild(item);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (null == mCurrentDir) {
				return super.onKeyDown(keyCode, event);
			}
			if (storageType == StorageType.MUILTY_TYPE) {
				if (rootDir == null) {
					setLeftButtonClickable(false);
					FolderBrowserActivity.this.finish();
					return super.onKeyDown(keyCode, event);
				} else {
					browseToParent(mCurrentDir);
					return false;
				}
			} else if (storageType == StorageType.SINGLE_TYPE) {
				if (mCurrentDir.equals(rootDir)) {
					setLeftButtonClickable(false);
					FolderBrowserActivity.this.finish();
					return super.onKeyDown(keyCode, event);
				} else {
					browseToParent(mCurrentDir);
					return false;
				}
			} else {
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void notifyDataSetChanged() {
		if (null != adapter) {
			// adapter.clearCacheState();
			// adapter.getIsSelected();
			adapter.notifyDataSetChanged();
		}
	}

}
